package h.ku.lang.modules.xml
{
	import h.ku.eval.Args;
	import h.ku.lang.hkuObject;

	public class hkuXML extends hkuObject
	{
		public var src:XML
		
		public static function xListToArr(x:XMLList):Array
		{
			var arr:Array = []
			for each(var y:XML in x){
				arr.push(new hkuXML(y))
			}
			return arr
		}
		
		public function hkuXML(src:XML)
		{
			this.src = src
				
			this.addAS3Function(":",function(a:Args):void
			{
				var arr:Array = []
				if(a.arguments[0] == '') a.arguments[0] = "*"
				var x:XMLList = src.child(a.arguments[0])
				var list:Array = xListToArr(x)
				if(list.length == 1){
					a.caller.finishFunctionEval(list[0])
				}
				a.caller.finishFunctionEval(list)
			})
				
			this.addAS3Function("parent",function(a:Args):void
			{
				a.caller.finishFunctionEval(new hkuXMLList(src.parent()))
			})
				
			this.addAS3Function("attrList",function(a:Args):void
			{
				var arr:Array = []
				var x:XMLList = src.attributes()
				for each(var y:XML in x){
					arr.push(y.toXMLString())
				}
				a.caller.finishFunctionEval(arr)
			})
				
			this.addAS3Function("attr",function(a:Args):void
			{
				try{
				if(a.arguments[0] == null){
					var at:XMLList = src.attributes()
					var obj:hkuObject = new hkuObject("<xml attr>")
					for each(var x:XML in at){
						obj.setProperty(x.name().localName,x.toXMLString())
					}
					a.caller.finishFunctionEval(obj)
				}else{
				if(a.arguments[1] == null){
					a.caller.finishFunctionEval(String(src["@"+a.arguments[0]]))
					return
				}else{
					src["@"+a.arguments[0]] = a.arguments[1]
					a.caller.finishFunctionEval(identity())
					return
				}
				}
				}catch(e:Error){
					a.caller.finishFunctionEval(false)
				}
			})
			
			this.addAS3Function("name",function(a:Args):void
			{
				var o:hkuObject = new hkuObject("<xml name>")
				o.setProperty("localName",src.name().localName)
				o.setProperty("uri",src.name().uri)
				a.caller.finishFunctionEval(o)
			})
				
			this.addAS3Function("val",function(a:Args):void
			{
				a.caller.finishFunctionEval(src.toString())
			})
				
			this.addAS3Function("descendants",function(a:Args):void
			{
				var d:XMLList = src.descendants()
				a.caller.finishFunctionEval(xListToArr(d))
			})
		}
		
		public override function self():*
		{
			return this.src
		}
		
		
		
		
		
		
		
	}
}